import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';  // 引入icon
import { message, Upload } from 'antd';  // 引入上传控件  和 消息控件
import React, { useState } from 'react';  

// 定义了叫  base64 的函数
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};


// 定义了一个叫做   beforeUpload的函数
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('请上传 JPG/PNG 文件!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('图片不可超过2MB!');
  }

  return isJpgOrPng && isLt2M;
};


// 定义组件
const App = () => {
  const [loading, setLoading] = useState(false);  // 定义一个变量 loading  默认值是 false
  const [imageUrl, setImageUrl] = useState();  // 定义了一个变量  imageUrl


  // 定义了一个函数   handleChange
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };


  // 定义了一个变量  uploadButton   值是html
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传头像
      </div>
    </div>
  );

  // 组件组件内容
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      action="/api/upload"
      showUploadList={false}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};


// 暴露组件
export default App;

